using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace Coffee.SurveyControls.SurveyQuestions
{

    /// <summary>
    /// Summary description for SQListBox
    /// </summary>
    public class SQCheckBoxList : SurveyQuestionRow
    {
        public SQCheckBoxList(SurveyControl parent, XmlNode configuration)
            : base(parent, configuration)
        {
        }

        public override void LoadDynamicData()
        {
            CheckBoxList cblcurr = (CheckBoxList)currentAnswerControl;
            Coffee.Binding.ConfigureBinding(cblcurr, rootNode);
            cblcurr.DataBind();
        }

        public override void LoadData()
        {
            Label tPrev = (Label)previousAnswerControl;
            CheckBoxList lbcurr = (CheckBoxList)currentAnswerControl;

            string current = ctlId;
            string currentype = "";

            // TODO: Fix mapping to SelectedIndex/Value

            if (rootNode.SelectSingleNode("mapping/current") != null)
            {
                currentype = rootNode.SelectSingleNode("mapping/current").Attributes["type"].Value;
                current = rootNode.SelectSingleNode("mapping/current/text()").Value;
            }

            if (Parent.Mapper != null)
            {
                tPrev.Text = (string)Parent.Mapper.Previous.GetProperty(ctlId);

                if (currentype == "index")
                    lbcurr.SelectedIndex = (int)Parent.Mapper.Current.GetProperty(current);
                else
                    lbcurr.SelectedValue = (string)Parent.Mapper.Current.GetProperty(current);
            }
        }

        public override void SaveData()
        {
            CheckBoxList lbcurr = (CheckBoxList)currentAnswerControl;

            string current = ctlId;
            string currentype = "";

            if (rootNode.SelectSingleNode("mapping/current") != null)
            {
                currentype = rootNode.SelectSingleNode("mapping/current").Attributes["type"].Value;
                current = rootNode.SelectSingleNode("mapping/current/text()").Value;
            }

            if (Parent.Mapper != null)
            {
                if (currentype == "index")
                    Parent.Mapper.Current.SetProperty(current, lbcurr.SelectedIndex);
                else
                    Parent.Mapper.Current.SetProperty(current, lbcurr.SelectedValue);
            }
        }

        protected override void Initialize()
        {

        }

        protected override Control CreateCurrentDataControl()
        {
            CheckBoxList cblcurr = new CheckBoxList();
            cblcurr.CssClass = "question";
            return cblcurr;
        }

        protected override Control CreatePreviousDataControl()
        {
            Label tprev = new Label();
            tprev.CssClass = "question";
            return tprev;
        }
    }
}